package com.zw.mes.module.technology.controller;


import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.zw.mes.base.BaseController;
import com.zw.mes.common.JsonResult;
import com.zw.mes.entity.technology.Result;
import com.zw.mes.module.cost.service.DictCommonService;
import com.zw.mes.module.technology.service.PurchasedService;
import com.zw.mes.util.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

import static com.zw.mes.constant.Constant.GROUP_SPECTYPE;

/**
 * @author mayongfeng
 * @version 1.0.0
 * @ClassName PurchasedController.java
 * @Description TODO
 * @createTime 2021年01月29日 09:06:00
 */
@Controller
@RequestMapping("/purch")
@SuppressWarnings("all")
public class PurchasedController extends BaseController {

    @Autowired
    private PurchasedService purchasedService;
    @Autowired
    private DictCommonService dictCommonService;

    /**
     * @Author mayongfeng
     * @Date 14:15 2021/1/29
     * @Description 页面跳转到外购件计划分配
     *
     **/
    @GetMapping
    public String listPage(Model model,Result result){
        model.addAttribute("special", dictCommonService.findDictByGroupName(GROUP_SPECTYPE));
//        model.addAttribute("sumNum",purchasedService.getSumNum(result));
        return "technology/purchased/listPage";
    }

    /**
     * @Author mayongfeng
     * @Date 14:15 2021/1/29
     * @Description 页面跳转到外购件计划分配
     *
     **/
    @GetMapping("/refreshNum")
    @ResponseBody
    public JsonResult refreshNum1(Result result){
       Result result1 = purchasedService.getSumNum(result);
        return JsonResult.success("",result1);
    }

    /**
     * @Author mayongfeng
     * @Date 14:24 2021/1/29
     * @Description 查询外购件计划分配列表
     *
     **/
    @PostMapping("/list")
    @ResponseBody
    public JsonResult listPurchased(Result result){
        startPage();
        List<Result> list = purchasedService.findWithReportQuery(result);
        return jsonResult(list);
    }

    /**
     * @Author mayongfeng
     * @Date 10:09 2021/2/20
     * @Description 查询明细
     *
     **/
    @GetMapping("/selectDetail")
    public String selectDetail(Integer id,Integer sheetType,
                               Model model){
        /** 通过Id查询该项目下的标头*/
        model.addAttribute("selectOne",purchasedService.getSelectById(id).get(0));
        /** 查询明细*/
        model.addAttribute("selectAll",purchasedService.getSelectDetail(id,sheetType));
        return "technology/purchased/selectPage";
    }

      /**
     * @Author mayongfeng
     * @Date 10:09 2021/2/20
     * @Description 查询明细
     *
     **/
    @GetMapping("/selectResult")
    public String selectDetail(String prodNo,Integer id, Model model){
        /** 通过Id查询该项目下的标头*/
        model.addAttribute("selectOne",purchasedService.getResultDetail(prodNo,id).get(0));
        /** 查询明细*/
        model.addAttribute("selectAll",purchasedService.getResultDetail(prodNo,id));
        return "technology/purchased/resultPage";
    }

    /**
     * @Author mayongfeng
     * @Date 13:13 2021/2/21
     * @Description 拆分页面
     *
     **/
    @GetMapping("/split/{id}")
    public String splitPage(@PathVariable("id") Integer id,Model model){
        /** 通过Id查询该项目下的标头*/
        model.addAttribute("selectOne",purchasedService.getSelectById(id).get(0));
        model.addAttribute("selectList",purchasedService.getSelectById(id));
        return "technology/purchased/splitPage";
    }

    /**
     * @Author mayongfeng
     * @Date 13:13 2021/2/21
     * @Description 变更拆分页面
     *
     **/
    @GetMapping("/changeSplit")
    public String changeSplit(Integer id,Model model){
        /** 通过Id查询该项目下的标头*/
        model.addAttribute("selectOne",purchasedService.getSelectById(id).get(0));
        model.addAttribute("selectList",purchasedService.getSelectById(id));
        model.addAttribute("selectAll",purchasedService.getChangeById(id));
        return "technology/purchased/changeSplitPage";
    }

 /**
     * @Author mayongfeng
     * @Date 13:13 2021/2/21
     * @Description 变更拆分验证页面
     *
     **/
    @PostMapping("/changeSplit/verify")
    @ResponseBody
    public JsonResult changeSplitVerifiy(Integer sheetId){

        int i = purchasedService.getSheetResult(sheetId);
        if(i==-1){
            return JsonResult.success("请先拆分原始单或者上一个变更单，再拆分此变更单！",i);
        }
        return jsonResult(i);
    }

    /**
     * 删除拆分后未下达的提报计划
     */
    @PostMapping("/delPlan")
    @ResponseBody
    public JsonResult resDelPlanSplit(Result result){
        int i = 0;
        i = purchasedService.resDelPlanSplit(result);
        if(i==-1){
            return JsonResult.success("已拆分的生产令未删除，不能提前删除提报计划，需要先删除生产令才能删除拆分提报计划！",i);
        }
        return jsonResult(i);
    }

    /**
     * @Author mayongfeng
     * @Date 8:31 2021/2/22
     * @Description 查询拆分页面的明细详情
     *
     **/
    @PostMapping("/planList")
    @ResponseBody
    public JsonResult planList(Result result){
        startPage();
        List<Result> list = purchasedService.findPlanListQuery(result);
        return jsonResult(list);
    }

    /**
     * @Author mayongfeng
     * @Date 8:31 2021/2/22
     * @Description 原始单自动拆分功能
     *
     **/
    @PostMapping("/autoSplit")
    @ResponseBody
    public JsonResult autoSplit(Result result){
        startPage();
        List<Result> list = purchasedService.findautoSplit(result);
        return jsonResult(list);
    }

    /**
     * @Author mayongfeng
     * @Date 8:31 2021/2/22
     * @Description 变更单自动拆分功能
     *
     **/
    @PostMapping("/autoChaSplit")
    @ResponseBody
    public JsonResult autoChaSplit(Result result){
        startPage();
        List<Result> list = purchasedService.autoChaSplit(result);
        return jsonResult(list);
    }

    /**
     * @Author mayongfeng
     * @Date 8:31 2021/2/22
     * @Description 自动拆分功能提交到输出表转给物控
     *
     **/
    @PostMapping("/confirm")
    @ResponseBody
    public JsonResult autoSplitCommit(String allTableData){
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm").create();
        List<Result> prodPlaDetList = gson.fromJson(allTableData, new TypeToken<List<Result>>() {}.getType());
        int b = purchasedService.isSumNum(prodPlaDetList);
        /** 验证相等*/
        if(b==-2){
            return JsonResult.success("手动分配的数量和,不等于提报计划的总数量,请检查!!!", -2);
        }

        return jsonResult(b);
    }

    /**
     * @Author mayongfeng
     * @Date 8:31 2021/2/22
     * @Description 自动拆分功能提交到输出表转给物控
     *
     **/
    @PostMapping("/confirmCha")
    @ResponseBody
    public JsonResult confirmCha(String allTableData){
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm").create();
        List<Result> prodChaDetList = gson.fromJson(allTableData, new TypeToken<List<Result>>() {}.getType());
        int b = purchasedService.isSumChaNum(prodChaDetList);
        /** 验证相等*/
        if(b==-2){
            return JsonResult.success("手动分配的数量和,不等于提报计划的总数量,请检查!!!", -2);
        }

        return jsonResult(b);
    }

    /**
     * @Author mayongfeng
     * @Date 10:09 2021/2/20
     * @Description 主表下达数据添加到输出表
     *
     **/
    @PostMapping("/sheetRelease")
    @ResponseBody
    public JsonResult sheetRelease(Integer resultAndSheetId,String prodNo){
        return purchasedService.addResultAndModifyLssue(resultAndSheetId);
    }
//    /**
//     * @Author mayongfeng
//     * @Date 10:09 2021/2/20
//     * @Description 退回到部长审核
//     *
//     **/
//    @PostMapping("/chaSheetReturn")
//    @ResponseBody
//    public JsonResult chaSheetReturn(String row){
//        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm").create();
//        Result result = gson.fromJson(row, Result.class);
//        int k = purchasedService.chaSheetReturn(result);
//        return jsonResult(k);
//    }
    /**
     * 20230617按照领导要求修改生产系统接收计划时必须添加驳回原因
     * */
    @PostMapping("/chaSheetReturn")
    @ResponseBody
    public  JsonResult chaSheetReturn(Result result){
        int i = purchasedService.chaSheetReturn(result);
        return jsonResult(i);
    }

    /**
     * @Author mayongfeng
     * @Date 10:09 2021/2/20
     * @Description 主表变更数据下达并且修改到输出表
     *
     **/
    @PostMapping("/chaSheetRelease")
    @ResponseBody
    public JsonResult chaSheetRelease(String row){
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm").create();
        Result result = gson.fromJson(row, Result.class);
        int i = purchasedService.chaSheetRelease(result);
        /** 判断I的状态*/
        if(i==-2){
            return JsonResult.success("请处理原始单或原始拆分单的计划是否下达或删除了！才能下达该计划",-2);
        }
        return jsonResult(i);
    }

    /**
     * @Author mayongfeng
     * @Date 10:09 2021/2/20
     * @Description 在输出表更改变更的数据下达的数据的状态
     *
     **/
    @PostMapping("/charesultRelease")
    @ResponseBody
    public JsonResult charesultRelease(String row){
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm").create();
        Result result = gson.fromJson(row, Result.class);
        int i = purchasedService.modifyLssue(result.getResultId(),result.getProdNo());
        return jsonResult(i);
    }

    /**
     * @Author mayongfeng
     * @Date 10:09 2021/2/20
     * @Description 在输出表更改下达的数据的状态
     *
     **/
    @PostMapping("/resultRelease")
    @ResponseBody
    public JsonResult resultRelease(Integer resultAndSheetId,String prodNo){
        int i = purchasedService.modifyLssue(resultAndSheetId,prodNo);
        if(i == -1){
            return JsonResult.success("生产令已删除，该拆分提报计划不允许下达！",-1);
        }
       return jsonResult(i);
    }
    /**
     * downloadProjectFile 请填写描述
     *
     * @param id 文件主键
     * @param httpServletResponse 下载相应体
     * @author 徐一贺
     * @date 2021/1/14 12:48
     */
    @GetMapping("/downloadProjectFile/{id}")
    public void downloadProjectFile(
            @PathVariable("id") Integer id, HttpServletResponse httpServletResponse) {
        try {
            Result result = purchasedService.getResultByid(id);
            String filename = result.getUrl();
            filename = filename.replace("/files/", "e:/pdm/upload/");

            FileUtils.downloadFile(filename, httpServletResponse);

        } catch (Exception exception) {
            exception.printStackTrace();
        }
    }
    @GetMapping("/downloadProjectFileAfter/{id}")
    public void downloadProjectFileAfter(
            @PathVariable("id") Integer id, HttpServletResponse httpServletResponse) {
        try {
            Result result = purchasedService.getResultByid(id);
            String filename = result.getAfterUrl();
            filename = filename.replace("/files/", "e:/pdm/upload/");

            FileUtils.downloadFile(filename, httpServletResponse);

        } catch (Exception exception) {
            exception.printStackTrace();
        }
    }
    @GetMapping("/downloadProjectFileOrig/{id}")
    public void downloadProjectFileOrig(
            @PathVariable("id") Integer id, HttpServletResponse httpServletResponse) {
        try {
            Result result = purchasedService.getPlanByid(id);
            String filename = result.getUrl();
            filename = filename.replace("/files/", "e:/pdm/upload/");

            FileUtils.downloadFile(filename, httpServletResponse);

        } catch (Exception exception) {
            exception.printStackTrace();
        }
    }

    /**
     * 分配页面数据导出
     * @param response
     * @param result
     */
    @ResponseBody
    @PostMapping("/prodOrdQuery/exportExcelBySearch")
    public void exportExcel(@RequestParam("sheetid") Integer sheetId,@RequestParam("sheetType") Integer sheetType, HttpServletResponse response) {
        if(sheetType == 1)
        {
            purchasedService.exportExcel(sheetId,response);
        }
        else if(sheetType == 2)
        {
            purchasedService.exportExcelChange(sheetId,response);
        }

    }





}
